/*!
sqlite的处理模块
*/
use lazy_static;

use rusqlite::{params, Connection, Result};
use serde::{Deserialize, Serialize};
use std::result::Result::Ok;
use std::sync::Mutex;

lazy_static! {
    /// 全局sqlite数据库地址
    ///
    /// Example:
    ///
    /// ```no_run,rust
    /// crate::sqlite::DB_PATH.lock().unwrap().set(path);
    /// ```
    pub static ref DB_PATH: Mutex<Path> = Mutex::new(Path { val: format!("") });
}

/// sqlite 数据库存放路径
pub struct Path {
    pub val: String,
}

impl Path {
    /// 设置存放路径
    pub fn set(&mut self, val: String) {
        self.val = val
    }
}

/// 初始化连接
///
/// Example:
///
/// ```no_run,rust
/// match sqlite::init() {
///     Ok(_) => true,
///     Err(e) => false,
/// }
/// ```
pub fn init() -> Result<()> {
    let conn = connect()?;
    create_connect_table(&conn)?;
    Ok(())
}

/// 打开一个sqlite数据库
pub fn connect() -> Result<Connection> {
    let conn = Connection::open(&DB_PATH.lock().unwrap().val)?;
    Ok(conn)
}
/// 创建一个连接表
fn create_connect_table(conn: &Connection) -> Result<()> {
    conn.execute(
        r#"CREATE TABLE IF NOT EXISTS connect (
                id              TEXT PRIMARY KEY,
                name            TEXT NOT NULL,
                address              TEXT NOT NULL,
                port            TEXT NOT NULL,
                password             TEXT
        );"#,
        params![],
    )?;
    Ok(())
}

/// redis 连接信息
#[derive(Debug, Serialize, Deserialize)]
pub struct Connect {
    id: String,
    name: String,
    address: String,
    port: String,
    password: String,
}
/// 查询redis连接信息list
pub fn query_conn_list() -> Result<Vec<Connect>> {
    let _sql = "select * from connect";
    let mut res: Vec<Connect> = vec![];
    if let Ok(mut stmt) = connect()?.prepare(_sql) {
        let mut rows = stmt.query([])?;
        while let Some(row) = rows.next()? {
            res.push(Connect {
                id: row.get("id")?,
                name: row.get("name")?,
                address: row.get("address")?,
                port: row.get("port")?,
                password: row.get("password")?,
            })
        }
    }

    Ok(res)
}
